import {
    Layer, Map
} from "../../modules/CloudMap/src/Cloud";
import {
    CFeature,
    CPoint,
    CSelect,
    CVector,
    COverlay,
    CCluster,
    CVectorLayer,
    CircleStyle,
    CText,
    CFill,
    CStroke,
    CStyle
} from "../../modules/CloudMap/src/modules/ol";
import { Component } from "react";
const scss = require('../../assets/styles/map.module.scss');

let click: any;

let overlay: any;
// 数据暂存
const count = 300000;
const features = new Array(count);


export default class PathPlan extends Component {
    layer: any;
    maps: any;
    state = {
        clickIs_: false,
        style: {
            symbol: {
                symbolType: 'circle',
                size: 16,
                color: '#ffed02',
                offset: [0, 0],
                opacity: 0.95
            },
        },
        vector: null,
        addIs_: false
    }
    componentDidMount() {
        this.initMap()
        this.initdata()
    }
    /**
     * 初始化地图
     */
    initMap = () => {
        // Initialize the cloud map
        this.layer = new Layer();
        // Creating a map object
        this.maps = new Map({ id: 'map', zoom: 10 });

    }
    /**
     * webGL 点位渲染/删除
     */
    clickOn = (sub: any) => {
        if (sub && this.state.addIs_) return;
        if (sub) {
            this.maps.addLayer(this.state.vector);
            this.featureClick(sub);
            this.setState({
                addIs_: sub
            })
        } else {
            // 移除点位，移除点击事件
            this.maps.removeLayer(this.state.vector);
            this.featureClick(sub);
            this.setState({
                addIs_: sub
            })
        }

    }
    // 数据初始化
    initdata = () => {

        for (let i = 0; i < count; ++i) {
            let lat = (count > 150000 ? Math.random() : -Math.random()) + 119.1;
            let lng = (count > 150000 ? Math.random() : -Math.random()) + 27.68;
            features[i] = new CFeature({
                text: `屏幕打点第${i}个`,
                geometry: new CPoint([lat, lng,]),
                id: i,
                size: 16,
                lat: lat,
                lng: lng,
                style: this.state.style,
            });
        }

        //聚合标注数据源
        var clusterSource = new CCluster({
            distance: 40,               //聚合的距离参数，即当标注间距离小于此值时进行聚合，单位是像素
            source: new CVector({
                features: features,
                wrapX: false,
            })              //聚合的数据源，即矢量要素数据源对象
        });
        // 创建webGl加载数据
        let vector = new CVectorLayer({
            zIndex: 10,
            source: clusterSource,
            style: function (feature, resolution) {
                var size = feature.get('features').length;          //获取该要素所在聚合群的要素数量
                let style = [
                    new CStyle({
                        image: new CircleStyle({
                            radius: 15,
                            stroke: new CStroke({
                                color: '#fff'
                            }),
                            fill: new CFill({
                                color: '#3399CC'
                            })
                        }),
                        text: new CText({
                            text: size.toString(),
                            fill: new CFill({
                                color: '#fff'
                            })
                        })
                    })
                ];


                return style;
            }

        });
        this.setState({
            vector
        });

    }
    /**
     * 
     * @param map 添加点击事件
     * @param clickIs_ 
     * @returns 
     */
    featureClick = (clickIs_: boolean) => {
        var container: any = document.getElementById('popup');
        var content = document.getElementById('popup-text');
        // 选择工作在“指针点击”上的交互
        const selectPointerMove = new CSelect({
            condition: click,
        });
        // 渲染点位增加事件
        clickIs_ ? this.maps.addInteraction(selectPointerMove) : this.maps.removeInteraction(selectPointerMove);
        if (!clickIs_) return;
        // 添加
        overlay = new COverlay(({
            element: container,
            autoPan: true,
            autoPanAnimation: {
                duration: 250   //当Popup超出地图边界时，为了Popup全部可见，地图移动的速度.
            }
        }));
        selectPointerMove.on('select', (e: any) => {
            overlay.setPosition(undefined);
            // content.innerHTML='<div></div>'
            if (!e.target.getFeatures().getArray()[0]) return;

            let _features = e.target.getFeatures().getArray()[0].values_.features;
            if (_features.length === 1) {
                // styleChangeClick(map,data);
                // e.target.getFeatures().getArray()[0].values_.getFeatures().clear();
                let data = _features[0].values_;
                if (content) {
                    try {
                        content.innerHTML = `<div>${data.text}</div>
                        <div>id: ${data.id}</div>
                        <div>经度: ${data.lat}</div>
                        <div>纬度: ${data.lng}</div>`;
                        // 标签记载位置
                        overlay.setPosition([data.lat, data.lng]);
                        this.maps.removeOverlay(overlay);
                        // 渲染到地图上面去
                        this.maps.addOverlay(overlay);
                    }
                    catch {
                        return
                    }
                }
            }


        });
    }

    render() {
        return (
            <div>
                <div
                    id={'map'}
                    className={scss['map']}
                ></div>
                <div className={scss['path-plan']}>
                    <span onClick={() => { this.clickOn(true) }}>打 点</span>
                    <span onClick={() => { this.clickOn(false) }}>清 除</span>
                </div>
                <div id={"popup"} className={scss['popup']}>
                    <div id={"popup-text"} className={scss['ol-popup']}>

                    </div>
                    <div className={scss['arrow']}></div>
                </div>
            </div>
        )
    }
}